package com.cus.tom.transfer.frag;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.R;
import com.cus.tom.transfer.adapter.BatchAdapter;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.databinding.ActivityDmBatchPhotoBinding;
import com.cus.tom.transfer.it.ImgUi;
import com.cus.tom.transfer.utils.Read;
import com.cus.tom.transfer.utils.Utils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ImgFragment extends BaseFragment implements ImgUi {

    protected ActivityDmBatchPhotoBinding binding;
    BatchAdapter adapter;
    int page = 0;
    boolean working = false;
    public final static Set<String> img = new HashSet<>();
    public final static Set<String> video = new HashSet<>();
    public final static Set<String> audio = new HashSet<>();
    final int type, index;

    public ImgFragment(int type, int index) {
        this.type = type;
        this.index = index;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = ActivityDmBatchPhotoBinding.inflate(inflater, container, false);
        if (type == 0) {
            binding.includeToolbar.back.setOnClickListener(v -> getActivity().finish());
            binding.includeToolbar.back.setText("全部照片");
        } else {
            binding.includeToolbar.getRoot().setBackgroundColor(0xfff3f3f3);
            binding.includeToolbar.back.setVisibility(View.INVISIBLE);
            binding.bottom.setVisibility(View.GONE);
        }
        binding.includeToolbar.all.setOnClickListener(v -> {
            boolean bo = !binding.includeToolbar.all.isSelected();
            binding.includeToolbar.all.setSelected(bo);
            adapter.selectAll(bo);
        });

        GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (adapter.getItemViewType(position) == 0) {
                    return 3;
                }
                return 1;
            }
        });
        binding.rvAlbum.setLayoutManager(manager);
        adapter = new BatchAdapter(this, 1);
        binding.rvAlbum.setAdapter(adapter);

        binding.next.setOnClickListener(v -> {
            recordSelect();
            Intent i = new Intent();
            i.putExtra("num", adapter.getSelectCount());
            i.putExtra("size", adapter.getSelectSize());
            getActivity().setResult(Activity.RESULT_OK, i);
            getActivity().finish();

//            if (from == 1) {
//                Intent i = new Intent();
//                i.putParcelableArrayListExtra("img", adapter.getSelect());
//                i.putExtra("position", getIntent().getIntExtra("position", -1));
//                setResult(RESULT_OK, i);
//                finish();
//            } else {
//                Intent i = new Intent(this, BatchPreviewAct.class);
//                i.putParcelableArrayListExtra("img", adapter.getSelect());
//                startActivityForResult(i, 11);
//            }
        });

        loadData(page);

        return binding.getRoot();
    }

    protected void recordSelect() {
        List<MediaData> list = adapter.getSelect();
        img.clear();
        for (MediaData item : list) {
            img.add(item.getPath());
        }
    }

    protected List<MediaData> getMediaData() {
        return new Read().loadImageData(App.getApp(), page, Integer.MAX_VALUE);
    }

    private boolean checkPermission() {
        if (!XXPermissions.isGranted(getActivity(), Permission.MANAGE_EXTERNAL_STORAGE)) {
            binding.bar1.setVisibility(View.INVISIBLE);
            binding.noDataTv.setVisibility(View.VISIBLE);
            adapter.setData(null, 0, 0, 0);
            binding.noDataTv.setText("去授权");
            binding.noDataTv.setTextColor(Color.WHITE);
            binding.noDataTv.setBackgroundResource(R.drawable.btn_bg);
            binding.noDataTv.setOnClickListener(v -> {
                reqPermission();
            });
            return false;
        }
        binding.noDataTv.setText("没有数据");
        binding.noDataTv.setTextColor(Color.LTGRAY);
        binding.noDataTv.setBackground(null);
        binding.noDataTv.setOnClickListener(null);
        return true;
    }

    private void reqPermission() {
        XXPermissions.with(this).permission(Permission.MANAGE_EXTERNAL_STORAGE).request(new OnPermissionCallback() {
            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                if (allGranted) {
                    loadData(0);
                }
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && adapter != null && adapter.getItemCount() == 0) {
            loadData(0);
        }
    }

    private boolean loadData(int page) {
        if (!checkPermission()) {
            return true;
        }
        if (working) {
            return false;
        }
        working = true;
        binding.bar1.setVisibility(View.VISIBLE);
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                try {
                    List<MediaData> list = getMediaData();
                    if (list == null || list.isEmpty()) {
                        if (page == 0) {
                            h.post(() -> {
                                binding.noDataTv.setVisibility(View.VISIBLE);
                                adapter.setData(null, 0, 0, 0);
                            });
                        }
                        return;
                    }
                    h.post(() -> binding.noDataTv.setVisibility(View.GONE));
                    if (list.size() == 1 && !list.get(0).isValid) {
                        return;
                    }
                    setOldData(list, getOldData());
                    long time = list.get(0).getAddTime();
                    int j = 0;
                    int num = 0;
                    long size = 0;
                    SparseArray<ArrayList<MediaData>> array = new SparseArray();
                    ArrayList<MediaData> l = new ArrayList();
                    l.add(list.get(0));
                    array.put(0, l);
                    for (int i = 1; i < list.size(); i++) {
                        MediaData m = list.get(i);
                        if (Utils.isSameDate(time, m.getAddTime())) {
                            l.add(m);
                        } else {
                            time = m.getAddTime();
                            ++j;
                            l = new ArrayList();
                            l.add(m);
                            array.put(j, l);
                        }
                        if (isInSelectedGroup(m) || m.isSetSelected()) {
                            ++num;
                            size += m.getSize();
                            m.setSetSelected(true);
                        }
                    }
                    if (isInSelectedGroup(list.get(0)) || list.get(0).isSetSelected()) {
                        ++num;
                        size += list.get(0).getSize();
                        list.get(0).setSetSelected(true);
                    }
                    list.clear();
                    ArrayList result = new ArrayList();
                    for (int i = 0; i < array.size(); i++) {
                        l = array.valueAt(i);
                        result.add(l.get(0).getAddTime());
                        result.addAll(l);
                    }
                    int i = num;
                    long ll = size;
                    h.post(() -> {
                        adapter.setData(result, page, i, ll);
                    });
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    h.post(() -> {
                        binding.bar1.setVisibility(View.INVISIBLE);
                        working = false;
                    });
                }
            }
        });
        return true;
    }

    protected Set<String> getOldData() {
        return img;
    }

    private void setOldData(List<MediaData> list, Set<String> set) {
        int num = set.size();
        if (num == 0) {
            return;
        }
        int i = 0;
        for (MediaData d : list) {
            if (set.contains(d.getPath())) {
                d.setSetSelected(true);
                if (++i == num) {
                    break;
                }
            }
        }
    }

    private boolean isInSelectedGroup(MediaData data) {
        Set<Long> set = adapter.getSelectGroup();
        for (Long l : set) {
            if (Utils.isSameDate(l, data.getAddTime())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public final void selectChange(int num, long size) {
        if (num <= 0) {
            binding.tip.setText(R.string.app_num0);
        } else {
            binding.tip.setText(String.format(getString(R.string.app_num), num, Utils.formatSize(size)));
        }
        if (type == 1) {
            recordSelect();
            ((FileFragment) getParentFragment()).updateBtn(num, index);
        }
    }
}
